package com.cma.typhoon.web.controller;

import com.cma.common.json.AjaxUtil;
import com.cma.model.db.LogInfo;
import com.cma.model.db.Tcrealtime;
import com.cma.model.param.HistctrackParam;
import com.cma.model.resultdb.DateTf;
import com.cma.service.HistctrackService;
import com.cma.service.LogInfoService;
import com.cma.service.TcrealtimeService;
import com.cma.util.BeansUtil;
import com.cma.util.ExcelUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.text.SimpleDateFormat;

/**
 * Created by bai on 2017/1/9.
 */
@Controller

@RequestMapping("/tfData")
public class TfDataController {

    @Autowired
    private TcrealtimeService tcrealtimeService;
    @Autowired
    private HistctrackService histctrackService;
    @Autowired
    private LogInfoService logInfoService;


    @RequestMapping("/tf_data.ajax")
    @ResponseBody
    public Map tfData(Model model,HistctrackParam histctrackParam){
        //TODO 根据台风编号查询台风数据

        return  null;
    }

    @RequestMapping("/test/{tfbhs}.ajax")
    @ResponseBody
    public Map tfData(@PathVariable String tfbhs){
        // TODO 查询日志记录

        Subject sub= SecurityUtils.getSubject();
        String userName= (String) sub.getPrincipal();
        if(!StringUtils.isEmpty(userName)){
            LogInfo logInfo=new LogInfo();
            logInfo.setUserName(userName);
            logInfo.setFtype("查询");
            logInfo.setFdesc("参数:tfbh"+tfbhs);
            logInfo.setCreateTime(new Date());
            logInfoService.save(logInfo);
        }
        //TODO 根据台风编号查询台风数据
        List list = histctrackService.qeuryByTfbh(tfbhs,null);
        Map map = new HashMap<>();
        map.put("result",list);
        return  map;
    }

    /**
     *根据台风编号来获取台风路径信息
     * @param model
     * @param bh //台风的编号
     * @param ty 是否是历史数据的标示 如果ty=his 则表示从历史库查询 如果ty=new 则表示从实时库中查询
     * @return
     */
    @RequestMapping("/tf_path_data/{ty}/{bh}.ajax")
    @ResponseBody
    public Map ftPathData(Model model, @PathVariable String bh,@PathVariable String ty){
        // TODO 查询日志记录

        Subject sub= SecurityUtils.getSubject();
        String userName= (String) sub.getPrincipal();
        if(!StringUtils.isEmpty(userName)){
            LogInfo logInfo=new LogInfo();
            logInfo.setUserName(userName);
            logInfo.setFtype("查询");
            logInfo.setFdesc("参数:bh"+bh+",ty:"+ty);
            logInfo.setCreateTime(new Date());
            logInfoService.save(logInfo);
        }
        Map<String,Object> resultMap = new HashMap<>();
        //如果传过来的ty值为his 则表示从历史库中查询数据
        if(!StringUtils.isEmpty(ty)&&ty.equals("his")){//历史数据
            //通过编号获取台风路径数据
            List<DateTf> list =    histctrackService.findPathData(bh);
            resultMap.put("tfbh",bh);//台风编号
            if(list.size()>0) {
                if (!StringUtils.isEmpty(list.get(0).getChnname())) {
                    String cname = list.get(0).getChnname();
                    try {
                        resultMap.put("name",cname );// new String(cname.getBytes("8859_1"), "GB2312"))
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    resultMap.put("name", list.get(0).getEngname());
                }
            }

            resultMap.put("pathData",list);
        }else{//否则的话直接从实时库中查询
            //通过编号获取台风路径数据
            List<Tcrealtime> list =  tcrealtimeService.findPathData(bh);
            resultMap.put("tfbh",list.get(0).getTfbh());
            if(list.size()>0) {
                if (!StringUtils.isEmpty(list.get(0).getChnname())) {
                    String cname1 = list.get(0).getChnname();
                    try {

                        resultMap.put("name",/* new String(cname1.getBytes("8859_1"), "GB2312")*/ cname1);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    resultMap.put("name", list.get(0).getEngname());
                }
            }
            resultMap.put("pathData",list);
        }

        return resultMap;
    }

    /**
     * 获取统计历年最大风速 历史库与实时库相结合  目前支持传入参数 lon lat  和 llWidth(经纬度范围半径)
     * @param model
     * @return
     */
    @RequestMapping("/tf_path_data/ftMaxWind.ajax")
    @ResponseBody
    public Map ftMaxWind(Model model,HistctrackParam histctrackParam){
        Map<String,String> map=tcrealtimeService.getMaxFs(histctrackParam);
        Map<String,String> map2=histctrackService.getMaxFs(histctrackParam);
        //结合一下 如果遍历实时库里面的统计 如果实时库里面有历史库中不存在的统计则添加进去
       for(Map.Entry<String,String> entry:map.entrySet()){
           if(!map2.containsKey(entry.getKey())){
               map2.put(entry.getKey(),entry.getValue());
           }
       }
        return  map2;
    }
    /**
     * 获取台风强度 统计 从历史库和实时库中获取 目前支持传入参数 lon lat  和 llWidth(经纬度范围半径)
     * @param model
     * @param histctrackParam
     * @return
     */
    @RequestMapping("/tf_path_data/ftStrength.ajax")
    @ResponseBody
    public Map ftStrength(Model model,HistctrackParam histctrackParam){
        Map<String,String> map=tcrealtimeService.getMaxStrength(histctrackParam);//从实时库中获取强度统计
        Map<String,String> map2=histctrackService.getMaxStrength(histctrackParam);//从历史库中获取强度统计
        //结合一下
        Map maps=new HashMap();
        maps.put("old",map2);
        maps.put("new",map);
        return  maps;
    }
    /***
     * 返回最新的实时路径
     * @param model
     * @return
     */
    @RequestMapping("/tf_path_data/realtime.ajax")
    @ResponseBody
    public Map ftPathData(Model model){
        Map<String,Object> resultMap = new HashMap<>();
        List<Tcrealtime> list=tcrealtimeService.findCrealtieData();
        resultMap.put("tfbh",list.get(0).getTfbh());
        if(!StringUtils.isEmpty(list.get(0).getChnname())){
            String cname=list.get(0).getChnname();
            try {
                //resultMap.put("name",new String(cname.getBytes("8859_1"),"GB2312"));
                resultMap.put("name",/* new String(cname1.getBytes("8859_1"), "GB2312")*/ cname);
            } catch (Exception e) {//UnsupportedEncodingException
                e.printStackTrace();
            }
        }else{
            resultMap.put("name",list.get(0).getEngname());
        }


        resultMap.put("pathData",list);
        return resultMap;
    }

    /**
     *导出excel文件----简版,复杂
     * @param tys  类型 列表 以逗号隔开 比如：his,his 等
     * @param bhs 编号 列表 以逗号隔开
     * @param  exceltype excel内容,简版 或者详细版
     */
    @RequestMapping("/exportDatasToExcel")
    public void exportDatasToExcel(String tys, String bhs, String exceltype, HttpServletResponse response){
        // TODO 记录用户导出日志记录
        Subject sub= SecurityUtils.getSubject();
        String userName= (String) sub.getPrincipal();
        if(!StringUtils.isEmpty(userName)){
            LogInfo logInfo=new LogInfo();
            logInfo.setUserName(userName);
            logInfo.setFtype("导出数据");
            logInfo.setFdesc("参数:tys："+tys+",bhs:"+bhs+",exceltype:"+exceltype);
            logInfo.setCreateTime(new Date());
            logInfoService.save(logInfo);
        }
        Map<String,Object> resultMap = new HashMap<>();
        String oldbh="";
        String newbh="";
        List<DateTf> list=null;
        List<Tcrealtime> list2=null;
        List<Tcrealtime> list3=null;
        if(!StringUtils.isEmpty(tys)){
            String[] ty=tys.split(",");
            String[] bh=bhs.split(",");
            if(ty.length>0){
                for(int i=0;i<ty.length;i++){
                    if(ty[i].equals("his")){
                        if(oldbh.length()>0){
                            oldbh=oldbh+","+bh[i];
                        }else{
                            oldbh=bh[i];
                        }
                    }else if(ty[i].equals("new")){
                        if(newbh.length()>0){
                            newbh=newbh+","+bh[i];
                        }else{
                            newbh=bh[i];
                        }
                    }
                }
            }

            if(oldbh.length()>0){
               list =histctrackService.findPathDatas(oldbh);
            }
            if(newbh.length()>0){
              list2=tcrealtimeService.findPathDatas(newbh);
            }
            list3= BeansUtil.conversionTtoforList(list,Tcrealtime.class);
            list3.addAll(list2);

        }
        OutputStream ops = null;
        String fileName="";
        //如果是简单格式
        if(exceltype.equals("simple")){
            //String[] fields, Map<String,String> fieldName, List<V> data
            String[] fields={"tfbh","datetime","lon","lat","windv","pressure"};
            Map map=new HashMap();
            map.put("tfbh","台风编号");
            map.put("datetime","时间");
            map.put("lon","经度(E)");
            map.put("lat","纬度(N)");
            map.put("windv","风速(m/s)");
            map.put("pressure","气压(HPA)");

            Date d = new Date();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

            String name = sdf.format(d);

            fileName="SimpleData_"+name+".xls";
            //fileName="simple_data.xls";

            response.setHeader("Content-Disposition", "attachment; filename="+fileName);
            response.setContentType("APPLICATION/OCTET-STREAM; charset=utf-8");
            HSSFWorkbook wb = null;
            try {
                ops = response.getOutputStream();
                //fieldStr前台必定传入值。所以，可以直接split()
                wb= (HSSFWorkbook) ExcelUtil.exportExc(fields,map,list3);
                wb.write(ops);
            }catch(IOException e){
                //log.info("输出文件发生错误==>"+e.getMessage());
            }finally {
                try{
                    ops.flush();
                    ops.close();
                }catch(Exception e ){
                }
            }
        }else if(exceltype.equals("normal")){
            String[] fields={"tfbh","engname","chnname","center","bwtype","FCSTType","datetime","fcsthour","strength","lon","lat",
                            "windv","pressure","movedir","movespeed","wind7class","wind7v1","wind7v2",
                            "wind7v3","wind7v4","wind10class","wind10v1","wind10v2","wind10v3","wind10v4","wind12class","wind12v1","wind12v2",
                            "wind12v3","wind12v4","wind6class","wind6v1","wind6v2","wind6v3","wind6v4"};

            Map map=new HashMap();
            map.put("tfbh","台风编号");
            map.put("engname","英文名称");
            map.put("chnname","中文名称");
            map.put("center","中心编号");
            map.put("bwtype","报文类型");
            map.put("FCSTType","预报方法");
            map.put("datetime","时间");
            map.put("fcsthour","时效");
            map.put("strength","强度");
            map.put("lon","经度(E)");
            map.put("lat","纬度(N)");
            map.put("windv","风速(m/s)");
            map.put("pressure","气压(HPA)");
            map.put("movedir","移向");
            map.put("movespeed","移速");
            map.put("wind7class","七级风圈");
            map.put("wind7v1","七级半径1");
            map.put("wind7v2","七级半径2");
            map.put("wind7v3","七级半径3");
            map.put("wind7v4","七级半径4");
            map.put("wind10class","十级风圈");
            map.put("wind10v1","十级半径1");
            map.put("wind10v2","十级半径2");
            map.put("wind10v3","十级半径3");
            map.put("wind10v4","十级半径4");
            map.put("wind12class","十二级风圈");
            map.put("wind12v1","十二级半径1");
            map.put("wind12v2","十二级半径2");
            map.put("wind12v3","十二级半径3");
            map.put("wind12v4","十二级半径4");
            map.put("wind6class","六级风圈");
            map.put("wind6v1","六级半径1");
            map.put("wind6v2","六级半径2");
            map.put("wind6v3","六级半径3");
            map.put("wind6v4","六级半径4");
            //strength

            Date d = new Date();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

            String name = sdf.format(d);

            fileName="NormalData_"+name+".xls";

            //fileName="normal-data.xls";

            response.setHeader("Content-Disposition", "attachment; filename="+fileName);
            response.setContentType("APPLICATION/OCTET-STREAM; charset=utf-8");
            HSSFWorkbook wb = null;
            try {
                ops = response.getOutputStream();
                //fieldStr前台必定传入值。所以，可以直接split()
                wb= (HSSFWorkbook) ExcelUtil.exportExc(fields,map,list3);
                wb.write(ops);
            }catch(IOException e){
                //log.info("输出文件发生错误==>"+e.getMessage());
            }finally {
                try{
                    ops.flush();
                    ops.close();
                }catch(Exception e ){
                }
            }
        }
        //如果是复杂格式
    }
}
